package com.bocloud.cmp.driver.providers.ali;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aliyuncs.ecs.model.v20140526.DescribeVRoutersRequest;
import com.aliyuncs.ecs.model.v20140526.DescribeVRoutersResponse;
import com.aliyuncs.ecs.model.v20140526.DescribeVRoutersResponse.VRouter;
import com.aliyuncs.exceptions.ClientException;
import com.bocloud.cmp.driver.providers.RouterDriver;
import com.bocloud.cmp.model.RouteModel;
import com.bocloud.cmp.model.RouterModel;
import com.bocloud.common.model.BsmResult;
import com.bocloud.common.utils.DateTools;
import com.google.common.collect.Lists;

public class AliRouterDriver extends AliDriver implements RouterDriver {

	private static Logger logger = LoggerFactory.getLogger(AliRouterDriver.class);

	public AliRouterDriver() {
		super();
	}

	public AliRouterDriver(String accessKey, String secretKey, String regionId) {
		super(accessKey, secretKey, regionId);
	}

	@Override
	public BsmResult sync() {
		DescribeVRoutersRequest request = new DescribeVRoutersRequest();
		request.setPageNumber(1);
		request.setPageSize(100);
		List<RouterModel> models = Lists.newArrayList();
		try {
			DescribeVRoutersResponse response = this.getClient().getAcsResponse(request);
			List<VRouter> routers = response.getVRouters();
			int totalCount = response.getTotalCount();
			for (VRouter router : routers) {
				models.add(this.convert(router));
			}
			int totalPage = totalCount / 100 + 1;
			if (totalPage == 1) {
				return new BsmResult(true, models, "success");
			}
			for (int i = 2; i <= totalPage; i++) {
				request.setPageNumber(i);
				request.setPageSize(100);
				response = this.getClient().getAcsResponse(request);
				routers = response.getVRouters();
				for (VRouter router : routers) {
					models.add(this.convert(router));
				}
			}
			return new BsmResult(true, models, "success");
		} catch (ClientException e) {
			logger.error("list routers error:", e);
			return new BsmResult(false, e.getErrCode(), e.getErrMsg());
		}

	}

	@Override
	public BsmResult create(RouteModel name) {
		return null;
	}

	@Override
	public BsmResult remove(String routerId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BsmResult detail(String routerId) {
		// TODO Auto-generated method stub
		return null;
	}

	private RouterModel convert(VRouter router) {
		if (null == router) {
			return null;
		}
		RouterModel model = new RouterModel(router.getVRouterId(), router.getVRouterName(), router.getDescription(),
				null, null, null, null);
		model.setGmtCreate(DateTools.transfer("yyyy-MM-dd'T'HH:mmZ", router.getCreationTime(), "Z"));
		return model;

	}

	@Override
	public BsmResult modify(RouteModel routeModel) {
		// TODO Auto-generated method stub
		return null;
	}
}
